<template>
  <div class="hello">
    <video id="remoteVideo" playsinline autoplay></video>

    <div class="box">
      <button id="startButton">Start</button>
      <button id="callButton">Call</button>
      <button id="hangupButton">Hang Up</button>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      remoteVideo: null,
      pc2: null,
      startButton: null,
      callButton: null,
      localVideo: null,
      hangupButton: null,
      socket: null,
    }
  },
  mounted() {
    this.startButton = document.getElementById('startButton')
    this.callButton = document.getElementById('callButton')
    this.hangupButton = document.getElementById('hangupButton')
    this.remoteVideo = document.getElementById('remoteVideo')
    this.startButton.addEventListener('click', this.start)
    this.callButton.addEventListener('click', this.call)
    this.hangupButton.addEventListener('click', this.hangup)
    this.initWebSockt()
  },
  methods: {
    hangup(){
      this.pc2.close()
      this.pc2 = null
      this.send({ toId: 1001, type: 8})
    },
    async call() {
      const configuration = {}
      this.pc2 = new RTCPeerConnection(configuration)
      this.pc2.addEventListener('icecandidate', (e) =>
        this.onIceCandidate(this.pc2, e)
      )
      this.pc2.addEventListener('iceconnectionstatechange', (e) =>
        this.onIceStateChange(this.pc2, e)
      )
      this.pc2.addEventListener('track', this.gotRemoteStream)
      this.send({ fromId: 1002, type: 4, toId: 1001 })
    },
    async start() {

      this.send({ toId: 1001, type: 7,capturer:1 })
    },
    gotRemoteStream(e) {
      if (this.remoteVideo.srcObject !== e.streams[0]) {
        this.remoteVideo.srcObject = e.streams[0]
        console.log('pc2 received remote stream')
      }
    },

    async onIceCandidate(pc, event) {
      try {
        this.send({
          fromId: 1002,
          toId: 1001,
          candidate: event.candidate,
          type: 3,
        })
        this.onAddIceCandidateSuccess(pc)
      } catch (e) {
        this.onAddIceCandidateError(pc, e)
      }
      console.log(
        `pc2 ICE candidate:\n${
          event.candidate ? event.candidate.candidate : '(null)'
        }`
      )
    },

    onAddIceCandidateSuccess() {
      console.log(`pc2 addIceCandidate success`)
    },

    onAddIceCandidateError(error) {
      console.log(`pc2 failed to add ICE Candidate: ${error.toString()}`)
    },

    onIceStateChange(pc, event) {
      if (pc) {
        console.log(`pc2 ICE state: ${pc.iceConnectionState}`)
        console.log('ICE state change event: ', event)
      }
    },

    onSetRemoteSuccess() {
      console.log(`pc2 setRemoteDescription complete`)
    },

    onSetSessionDescriptionError(error) {
      console.log(`Failed to set session description: ${error.toString()}`)
    },
    async onCreateAnswerSuccess(desc) {
      console.log(`Answer from pc2:\n${desc.sdp}`)
      console.log('pc2 setLocalDescription start')
      try {
        await this.pc2.setLocalDescription(desc)
        this.send({ fromId: 1002, toId: 1001, type: 2, desc: desc })
        this.onSetLocalSuccess(this.pc2)
      } catch (e) {
        this.onSetSessionDescriptionError(e)
      }
    },
    onSetLocalSuccess() {
      console.log(`pc2 setLocalDescription complete`)
    },
    onCreateSessionDescriptionError(error) {
      console.log(`Failed to create session description: ${error.toString()}`)
    },
    async pc2createAnswer() {
      try {
        const answer = await this.pc2.createAnswer()
        console.log(answer + 'hahahahha')
        this.onCreateAnswerSuccess(answer)
      } catch (e) {
        this.onCreateSessionDescriptionError(e)
      }
    },

    async remoteDesc(data) {
      try {
        await this.pc2.setRemoteDescription(data.desc)
        await this.onSetRemoteSuccess(this.pc2)
        await this.pc2createAnswer()
      } catch (e) {
        this.onSetSessionDescriptionError(e)
      }
    },

    initWebSockt: function() {
      if (!window.WebSocket) {
        // 有的浏览器里可能没有Websocket对象，window就代表浏览器，就做一下兼容性处理
        window.WebSocket = window.MozWebSocket
      }
      if (window.WebSocket) {
        var _this = this
        this.socket = new WebSocket('ws://192.168.0.199:8100/websocket') // 使用userId作为请求识别
        this.socket.onmessage = function(event) {
          // 收到客户端消息
          var data = JSON.parse(event.data)

          console.log(data)
          if (data.type === 2) {
            _this.remoteDesc(data)
          } else if (data.type === 3) {
            _this.pc2.addIceCandidate(data.candidate)
          }else if (data.type === 6){
            _this.hangup()
          }
        }
        this.socket.onopen = function(event) {
          console.log(event)

          _this.send({ fromId: 1002, type: 1 })
        }

        this.socket.onclose = function(event) {
          console.log(event)
          _this.hangup()
        }

        this.socket.onerror = function(event) {
          console.log(event)
          _this.hangup()
        }
        // socket不断接受服务端传来的数据，然后通过三个事件进行处理
      }
    },
    // 客户端想发送数据
    send: function(msg) {
      if (!window.WebSocket) {
        return false
      }
      if (this.socket.readyState === WebSocket.OPEN) {
        this.socket.send(JSON.stringify(msg))
        console.log(JSON.stringify(msg))
      } else {
        alert('连接没有建立')
      }
    },
  },
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h3 {
  margin: 40px 0 0;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}

/*
 *  Copyright (c) 2015 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree.
 */
button {
  margin: 0 20px 0 0;
  width: 83px;
}

button#hangupButton {
  margin: 0;
}

video {
  --width: 45%;
  width: var(--width);
  height: calc(var(--width) * 0.75);
  margin: 0 0 20px 0;
  vertical-align: top;
}

video#localVideo {
  margin: 0 20px 20px 0;
}

div.box {
  margin: 1em;
}

@media screen and (max-width: 400px) {
  button {
    width: 83px;
    margin: 0 11px 10px 0;
  }

  video {
    height: 90px;
    margin: 0 0 10px 0;
    width: calc(50% - 7px);
  }
  video#localVideo {
    margin: 0 10px 20px 0;
  }
}
</style>
